package com.zat.mes.andrmes.dofun.work

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.media.RingtoneManager
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.data.*
import com.zat.mes.andrmes.dofun.QrScanActivity
import com.zat.mes.andrmes.dofun.work.adapter.InhouseOrderProductAdapter
import com.zat.mes.andrmes.dofun.work.vm.OutSourceModel
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.utils.DateUtil
import com.zat.mes.andrmes.utils.ReadCardUtils
import com.zat.mes.andrmes.utils.SystemActivityUtil
import com.zat.mes.andrmes.utils.showToast
import kotlinx.android.synthetic.main.activity_out_source_inhouse.*
import kotlinx.android.synthetic.main.dialog_bom_inhouse.view.*
import kotlinx.android.synthetic.main.dialog_bom_outhouse.view.*
import kotlinx.android.synthetic.main.dialog_pack_inhouse.*
import kotlinx.android.synthetic.main.dialog_pack_inhouse.view.*
import kotlinx.android.synthetic.main.dialog_pack_outhouse.*
import kotlinx.android.synthetic.main.dialog_pack_outhouse.view.*
import kotlinx.android.synthetic.main.header_view_inhouse.view.*
import kotlinx.android.synthetic.main.item_recallplan.view.*
import kotlinx.android.synthetic.main.layout_title.*
import permissions.dispatcher.*
import java.util.*
import kotlin.collections.ArrayList

/**
 * 外协出入库
 */
@RuntimePermissions
class OutSourceInHouseActivity : BaseActivity() {

    private var outSourceModel: OutSourceModel? = null

    //U口读卡器,类似于外接键盘
    private var readCardUtils: ReadCardUtils? = null
    private var orderBom: OutsourceOrderBom? = null
    private var cutpackage: OutsourceCutpackage? = null
    //外协单 成品入库用
    private var outSourceBean: OutSourceBean? = null

    override fun init() {
        initView()
        initData()
    }


    private fun initData() {
        //读卡器声明
        readCardUtils = ReadCardUtils()
        initCardReader()

        recyclerProductInhouse.layoutManager = LinearLayoutManager(this)
        val inhouseOrderProductAdapter =
            InhouseOrderProductAdapter(R.layout.item_order_product_inthouse)
        recyclerProductInhouse.adapter = inhouseOrderProductAdapter

        outSourceModel = ViewModelProvider(this).get(OutSourceModel::class.java);
        outSourceModel?.getOutsourceList()?.observe(this, Observer {
            closeLoading()
            if (it != null) {
                produceNameOutSource.text = it?.productName
                orderNoOutSource.text = it?.orderId
                styleNoOutSource.text = it?.styleNo
                if ("1" == it?.outsourceType) {
                    typeNameOutSource.text = getString(R.string.text_all_outsource)
                } else if ("2" == it?.outsourceType) {
                    typeNameOutSource.text = getString(R.string.text_proc_outsource)
                }
                outHouseNoOutSource.text = it?.outsourceId
                comePanyNameOutSource.text = it?.osfactoryName
                outHouseTimeOutSource.text = it?.outDate

                if (it?.outsourceCutpackageList != null && it?.outsourceCutpackageList.size > 0) {
                    //裁片包
                    llBomOutSource.visibility = View.GONE
                    llProductOutSource.visibility = View.GONE
                    llPackOutSource.visibility = View.VISIBLE
                    val outsourceCutpackage = it?.outsourceCutpackageList.get(0)

                    if (outsourceCutpackage?.outQuantity!=null && outsourceCutpackage?.outQuantity.toInt()>0){
                        //入库
                        btnPackInhouse.text = getString(R.string.text_inhouse)

                    }else{
                        //出库
                        btnPackInhouse.text = getString(R.string.text_outhouse)

                    }
                    setPackText(outsourceCutpackage)
                } else if (it?.outsourceOrderBomList != null && it?.outsourceOrderBomList.size > 0) {
                    //bom 单
                    llBomOutSource.visibility = View.VISIBLE
                    llPackOutSource.visibility = View.GONE
                    llProductOutSource.visibility = View.GONE
                    val outsourceOrderBom = it?.outsourceOrderBomList.get(0)

                    if (outsourceOrderBom?.practicaloutQty!=null &&outsourceOrderBom?.practicaloutQty.toDouble()>0){
                        //入库
                        btnBomInhouse.text = getString(R.string.text_inhouse)
                    }else{
                        //出库
                        btnBomInhouse.text = getString(R.string.text_outhouse)
                    }
                    setBomText(outsourceOrderBom)

                } else if (it?.outsourceOrderDetails != null && it?.outsourceOrderDetails.size > 0) {
                    //整单
                    outSourceBean = it
                    llBomOutSource.visibility = View.GONE
                    llPackOutSource.visibility = View.GONE
                    llProductOutSource.visibility = View.VISIBLE

                    if (it?.outsourceOrderDetails.get(0)?.outquantity!=null && it?.outsourceOrderDetails.get(0)?.outquantity.toInt()>0){
                        //入库
                        btnProductInhouse.text = "入库"
                        inhouseOrderProductAdapter.inHouse = true
                        val headerView = LayoutInflater.from(baseContext)
                            .inflate(R.layout.header_view_inhouse, null)
                        inhouseOrderProductAdapter.addHeaderView(headerView)
                        if(it?.outsourceRecallplanList==null || it?.outsourceRecallplanList?.size!! <=0){
                            headerView.tvHasInQty.text = "0"
                            headerView.llRecallplan.visibility = View.GONE
                        }else{
                            headerView.llRecallplan.visibility = View.VISIBLE
                            var inQty = 0
                            for (realCallBean in it?.outsourceRecallplanList!!){
                                if(realCallBean.inrecallqty==null){
                                    realCallBean.inrecallqty = 0
                                }
                                inQty += realCallBean.inrecallqty!!
                                val itemRealView = LayoutInflater.from(baseContext)
                                    .inflate(R.layout.item_recallplan, null)
                                headerView.llRecallplan.addView(itemRealView)
                                itemRealView.tvInrealQtyItem.text = realCallBean.recallQty.toString()+"/"+realCallBean.inrecallqty.toString()
                                if(realCallBean.recallDate==null){
                                    realCallBean.recallDate = ""
                                }
                                itemRealView.tvInrealDateItem.text= realCallBean.recallDate+"/"+realCallBean.inrecallDate
                            }
                            headerView.tvHasInQty.text = inQty.toString()
                        }


                        for (produce in it?.outsourceOrderDetails) {
                            if (produce.inquantity==null){
                                produce.oldInquantity = 0
                            }else{
                                produce.oldInquantity = produce.inquantity.toInt()
                            }
                            try {
                                produce.inquantity = (produce.outquantity.toInt() - produce.inquantity.toInt()).toString()
                            }catch (e:java.lang.Exception){}

                        }
                        if ("0"==headerView.tvHasInQty.text.toString()) {
                            for (produce in it?.outsourceOrderDetails) {
                                produce.inquantity = produce.outquantity
                            }
                        }
                    }else{
                        //出库
                        btnProductInhouse.text = "出库"
                        inhouseOrderProductAdapter.inHouse = false
                        for (produce in it?.outsourceOrderDetails){
                            produce.outquantity = produce.quantity
                        }
                    }
                    inhouseOrderProductAdapter.setNewData(it?.outsourceOrderDetails as MutableList<OutsourceOrderDetail>?)
                } else {
                    showToast(getString(R.string.text_not_find))
                }
            } else {
                showToast(getString(R.string.text_not_find))
            }
        })
        outSourceModel?.getOutsourcePostData()?.observe(this, Observer {
            closeLoading()
            showToast(it)
            finish()
        })

    }

    private fun setBomText(bom: OutsourceOrderBom) {
        orderBom = bom
        bomNoOutSource.text = bom.materialNO
        bomNameOutSource.text = bom.materialName
        bomDanweiOutSource.text = bom.main_unit
        fudanweiOutSource.text = bom.unit
        danhaoOutSource.text = bom.unitWaste
        if("入库".equals(btnBomInhouse.text.toString())){
            tvTypefuBom.text = getString(R.string.unit_fu_qyt_in)
            tvTypezhuBom.text = getString(R.string.unit_zhu_qty_in)
            zhuChuQtyOutSource.text = bom.outmainoutQty
            fuChuQtyOutSource.text = bom.outunitoutQty
        }else{
            tvTypefuBom.text = getString(R.string.unit_fu_qyt)
            tvTypezhuBom.text = getString(R.string.unit_zhu_qty)
            zhuChuQtyOutSource.text = bom.mainoutQty
            fuChuQtyOutSource.text = bom.unitoutQty
        }


    }

    private fun setPackText(pack: OutsourceCutpackage) {
        cutpackage = pack
        packNoOutSource.text = pack.packNO
        packStyleNoOutSource.text = pack.styleNo
        packColorOutSource.text = pack.color
        packSizeOutSource.text = pack.size
        if("入库".equals(btnPackInhouse.text.toString())) {
            tvTypePack.text = getString(R.string.inhouse_qty)
            packOutQtyOutSource.text = pack.outQuantity
        }else{
            tvTypePack.text = getString(R.string.out_house_qty)
            packOutQtyOutSource.text = pack.quantity
        }
    }

    private fun initView() {
        setContentView(R.layout.activity_out_source_inhouse)
        tVtitle.text = getString(R.string.title_outsource)
        rlReturnTitle.visibility = View.VISIBLE
        rlReturnTitle.setOnClickListener { finish() }
        btnSanOutsource.setOnClickListener {
            showCameraWithPermissionCheck()
        }

        btnBomInhouse.setOnClickListener {
            if ("入库".equals(btnBomInhouse.text.toString())) {
                val bomView = LayoutInflater.from(this).inflate(R.layout.dialog_bom_inhouse, null)

                val bomBuilder = AlertDialog.Builder(this)
                    .setView(bomView)
                val bomDialog = bomBuilder.show();
                bomView.btnBomCancelDialog.setOnClickListener { bomDialog.dismiss() }
                bomView.btnBomOkDialog.setOnClickListener {
                    if (TextUtils.isEmpty(bomView.etzhuQtyDialog.text.toString())) {
                        showToast(getString(R.string.text_input_zhu_qty))
                        return@setOnClickListener
                    }
                    if (TextUtils.isEmpty(bomView.etBomFuQtyDialog.text.toString())) {
                        showToast(getString(R.string.text_input_fu_qty))
                        return@setOnClickListener
                    }
//                if (TextUtils.isEmpty(bomView.etQtyDialog.text.toString())){
//                    showToast("请输入入库数")
//                    return@setOnClickListener
//                }
                    bomDialog.dismiss()
                    showLoading()
//                orderBom?.inQty = bomView.etzhuQtyDialog.text.toString()
                    orderBom?.inmainoutQty = bomView.etzhuQtyDialog.text.toString()
                    orderBom?.inunitoutQty = bomView.etBomFuQtyDialog.text.toString()
                    orderBom?.inQty = (bomView.etzhuQtyDialog.text.toString().toDouble()+bomView.etBomFuQtyDialog.text.toString().toDouble()).toString()
                    var jsonArray = Gson().toJson(orderBom)
                    outSourceModel?.loadInhouseBom(jsonArray)
                }
            }else{
                //出库
                val bomView = LayoutInflater.from(this).inflate(R.layout.dialog_bom_outhouse, null)

                val bomBuilder = AlertDialog.Builder(this)
                    .setView(bomView)
                val bomDialog = bomBuilder.show();
                bomView.btnBomCancelDialogOut.setOnClickListener { bomDialog.dismiss() }
                bomView.btnBomOkDialogOut.setOnClickListener {
                    if (TextUtils.isEmpty(bomView.etzhuQtyDialogOut.text.toString())) {
                        showToast(getString(R.string.text_input_zhu_qty_out))
                        return@setOnClickListener
                    }
                    if (TextUtils.isEmpty(bomView.etBomFuQtyDialogOut.text.toString())) {
                        showToast(getString(R.string.text_input_fu_qty_out))
                        return@setOnClickListener
                    }
                    bomDialog.dismiss()
                    showLoading()
                    orderBom?.outmainoutQty = bomView.etzhuQtyDialogOut.text.toString()
                    orderBom?.outunitoutQty = bomView.etBomFuQtyDialogOut.text.toString()
                    orderBom?.practicaloutQty = (bomView.etzhuQtyDialogOut.text.toString().toDouble()+ bomView.etBomFuQtyDialogOut.text.toString().toDouble()).toString()
                    var jsonArray = Gson().toJson(orderBom)
                    outSourceModel?.loadInhouseBom(jsonArray)
                }

            }

        }
        btnPackInhouse.setOnClickListener {
            if ("入库".equals(btnPackInhouse.text.toString())) {
                val packView = LayoutInflater.from(this).inflate(R.layout.dialog_pack_inhouse, null)
                val packBuilder = AlertDialog.Builder(this)
                    .setView(packView)
                val packDialog = packBuilder.show();
                packView.btnPackCancelDialog.setOnClickListener { packDialog.dismiss() }
                packDialog.btnPackOkDialog.setOnClickListener {
                    if (TextUtils.isEmpty(packView.etAQtyDialog.text.toString())) {
                        showToast(getString(R.string.text_input_a_qty))
                        return@setOnClickListener
                    }
                    if (TextUtils.isEmpty(packView.etBQtyDialog.text.toString())) {
                        showToast(getString(R.string.text_input_b_qty))
                        return@setOnClickListener
                    }
                    if (TextUtils.isEmpty(packView.etFxQtyDialog.text.toString())) {
                        showToast(getString(R.string.text_input_repair_qty))
                        return@setOnClickListener
                    }
                    packDialog.dismiss()
                    showLoading()
                    cutpackage?.aqty = packView.etAQtyDialog.text.toString()
                    cutpackage?.bqty = packView.etBQtyDialog.text.toString()
                    cutpackage?.repairQty = packView.etFxQtyDialog.text.toString()
                    cutpackage?.inQty = (packView.etAQtyDialog.text.toString().toInt()+ packView.etBQtyDialog.text.toString().toInt()).toString()
                    cutpackage?.status = "6"
                    outSourceModel?.loadInhousePack(Gson().toJson(cutpackage))
                }
            }else{
                //出库
                val outPackView = LayoutInflater.from(this).inflate(R.layout.dialog_pack_outhouse, null)
                val packBuilder = AlertDialog.Builder(this)
                    .setView(outPackView)
                val outPackDialog = packBuilder.show()
                outPackView.btnPackOutCancelDialog.setOnClickListener { outPackDialog.dismiss() }
                outPackDialog.btnPackOutOkDialog.setOnClickListener {
                    if (TextUtils.isEmpty(outPackView.etRealQtyDialog.text.toString())) {
                        showToast(getString(R.string.text_input_real_qty))
                        return@setOnClickListener
                    }
                    outPackDialog.dismiss()
                    showLoading()
                    cutpackage?.outQuantity = outPackView.etRealQtyDialog.text.toString()
                    cutpackage?.status = "5"
                    outSourceModel?.loadInhousePack(Gson().toJson(cutpackage))
                }

            }
        }

        btnProductInhouse.setOnClickListener {
//            val orderView =
//                LayoutInflater.from(this).inflate(R.layout.dialog_order_product_inhouse, null)
//            val orderBuilder = AlertDialog.Builder(this)
//                .setView(orderView)
//            val orderDialog = orderBuilder.show();
//            orderView.btnProductCancelDialog.setOnClickListener { orderDialog.dismiss() }
//            orderView.btnProductOkDialog.setOnClickListener {
//                if (TextUtils.isEmpty(orderView.etAQtyProductDialog.text.toString())) {
//                    showToast(getString(R.string.text_input_a_qty))
//                    return@setOnClickListener
//                }
//                if (TextUtils.isEmpty(orderView.etBQtyProductDialog.text.toString())) {
//                    showToast(getString(R.string.text_input_b_qty))
//                    return@setOnClickListener
//                }
//                orderDialog.dismiss()
                showLoading()
//                outSourceBean?.Aquert = orderView.etAQtyProductDialog.text.toString()
//                outSourceBean?.Bquert = orderView.etBQtyProductDialog.text.toString()
                if(outSourceBean?.outsourceRecallplanList==null){
                    outSourceBean?.outsourceRecallplanList = ArrayList()
                }
                if (outSourceBean?.outsourceRecallplanList?.size!! <=0){
                    //新建一条
                    var inQty = 0
                    for (orderDetail in outSourceBean?.outsourceOrderDetails!!){
                        if (orderDetail.inquantity==null){
                            orderDetail.inquantity = "0"
                        }
                        inQty+=orderDetail.inquantity.toInt()
                        orderDetail.inquantity = (orderDetail.inquantity.toInt()+orderDetail.oldInquantity).toString()
                    }
                    val recallplan = Recallplan(null,null,null,DateUtil.formatDate(Date()),0,inQty)
                    outSourceBean?.outsourceRecallplanList?.add(recallplan)
                }else{
                    //找出为0 的那一条，如果没有，则新加入一条
                    var toRecallBean:Recallplan?=null
                    for (recall in outSourceBean?.outsourceRecallplanList!!){
                        if(recall.inrecallqty==null || recall.inrecallqty==0){
                            toRecallBean = recall
                            break
                        }
                    }
                    if (toRecallBean==null){
                        //新建一条
                        var inQty = 0
                        for (orderDetail in outSourceBean?.outsourceOrderDetails!!){
                            if(orderDetail.inquantity==null){
                                orderDetail.inquantity="0"
                            }
                            inQty+=orderDetail.inquantity.toInt()
                            orderDetail.inquantity = (orderDetail.inquantity.toInt()+orderDetail.oldInquantity).toString()
                        }
                        val recallplan = Recallplan(null,null,null,DateUtil.formatDate(Date()),0,inQty)
                        outSourceBean?.outsourceRecallplanList?.add(recallplan)
                    }else{
                        //赋值 入库数
                        var inQty = 0
                        for (orderDetail in outSourceBean?.outsourceOrderDetails!!){
                            if (orderDetail.inquantity==null){
                                orderDetail.inquantity = "0"
                            }
                            inQty+=orderDetail.inquantity.toInt()
                            orderDetail.inquantity = (orderDetail.inquantity.toInt()+orderDetail.oldInquantity).toString()
                        }
                        toRecallBean.inrecallqty = inQty
                        toRecallBean.inrecallDate = DateUtil.formatDate(Date())
                    }

                }
                outSourceModel?.loadInhouseProduct(Gson().toJson(outSourceBean))

//            }

        }
    }

    private fun requestData() {

    }

    private fun initCardReader() {

        readCardUtils?.setReadSuccessListener(ReadCardUtils.OnReadSuccessListener() {
            Log.e("zhangyucode", "barcode: " + it);
            if (it.length == 8 || it.length == 10) {
                //叫唤
                val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                val r = RingtoneManager.getRingtone(applicationContext, notification)
                r.play()
//                val soundPool = SoundPool(2, AudioManager.STREAM_MUSIC, 0)
//                soundPool.load(this,R.raw.ondo,1)
//                soundPool.play(1,1f, 1f, 0, 0, 1f);
//                showLoading()
//                recordViewModel?.loadPackDataByRFRDUpdate(it)
                showLoading()
                outSourceModel?.loadInhouseList(2, it);
            }
        });
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val qrCode = data?.getStringExtra(CompanionType.INTENT_EXTRA_QRCODE)
        if (resultCode == Activity.RESULT_OK) {
            //根据二维码查包
            showLoading()
            outSourceModel?.loadInhouseList(1, qrCode);
        }
    }


    @NeedsPermission(Manifest.permission.CAMERA)
    fun showCamera() {
        try {
            startActivityForResult(Intent(this, QrScanActivity::class.java), 0)
        } catch (e: Exception) {
            Log.e("activity", e.toString())
        }
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    fun showRationaleForCamera(request: PermissionRequest) {
        request.proceed();
        Log.e("permission", "OnShowRationale")
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    fun onCameraDenied() {
        showCameraWithPermissionCheck()
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    fun onCameraNeverAskAgain() {
//        showToast("请到设置打开相机权限")
        SystemActivityUtil.getAppDetailSettingIntent(this)
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)

    }

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        if (ReadCardUtils.isInputFromReader(this, event)) {
            if (readCardUtils != null) {
                readCardUtils?.resolveKeyEvent(event);
            }
        }
        return super.dispatchKeyEvent(event);

    }

    override fun onDestroy() {
        readCardUtils?.removeScanSuccessListener();
        readCardUtils = null;
        super.onDestroy()
    }

}
